package com.quaidi.smartlocker.controller;

import com.quaidi.smartlocker.annotation.RequireRole;
import com.quaidi.smartlocker.common.Result;
import com.quaidi.smartlocker.entity.LockerCompartment;
import com.quaidi.smartlocker.enums.UserRole;
import com.quaidi.smartlocker.service.LockerCompartmentService;
// import io.swagger.annotations.Api;
// import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 智能柜格Controller
 * 
 * @author QuaiDi
 * @since 2025-08-26
 */
// @Api(tags = "智能柜格管理")
@RestController
@RequestMapping("/api/compartments")
public class LockerCompartmentController {

    @Autowired
    private LockerCompartmentService lockerCompartmentService;

    /**
     * 获取所有柜格
     */
    // @ApiOperation("获取所有柜格")
    @GetMapping("/all")
    public Result<List<LockerCompartment>> getAllCompartments() {
        List<LockerCompartment> compartments = lockerCompartmentService.list();
        return Result.success(compartments);
    }

    /**
     * 按楼层获取柜格
     */
    // @ApiOperation("按楼层获取柜格")
    @GetMapping("/by-floor")
    public Result<Map<Integer, List<LockerCompartment>>> getCompartmentsByFloor() {
        Map<Integer, List<LockerCompartment>> compartmentsByFloor = 
            lockerCompartmentService.getCompartmentsByFloor();
        return Result.success(compartmentsByFloor);
    }

    /**
     * 获取柜格状态统计
     */
    // @ApiOperation("获取柜格状态统计")
    @GetMapping("/statistics")
    public Result<Map<String, Long>> getCompartmentStatistics() {
        Map<String, Long> statistics = lockerCompartmentService.getCompartmentStatusStatistics();
        return Result.success(statistics);
    }

    /**
     * 根据ID获取柜格详情 - 管理员功能
     */
    // @ApiOperation("获取柜格详情")
    @RequireRole(UserRole.ADMIN)
    @GetMapping("/{id}")
    public Result<LockerCompartment> getCompartmentById(@PathVariable Long id) {
        LockerCompartment compartment = lockerCompartmentService.getById(id);
        if (compartment == null) {
            return Result.error("柜格不存在");
        }
        return Result.success(compartment);
    }

    /**
     * 新增柜格 - 管理员功能
     */
    // @ApiOperation("新增柜格")
    @RequireRole(UserRole.ADMIN)
    @PostMapping
    public Result<String> createCompartment(@RequestBody LockerCompartment compartment) {
        try {
            boolean success = lockerCompartmentService.createCompartmentWithValidation(compartment);
            if (success) {
                return Result.success("柜格创建成功");
            } else {
                return Result.error("柜格创建失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新柜格信息 - 管理员功能
     */
    // @ApiOperation("更新柜格信息")
    @RequireRole(UserRole.ADMIN)
    @PutMapping("/{id}")
    public Result<String> updateCompartment(@PathVariable Long id, @RequestBody LockerCompartment compartment) {
        try {
            boolean success = lockerCompartmentService.updateCompartmentWithValidation(id, compartment);
            if (success) {
                return Result.success("柜格更新成功");
            } else {
                return Result.error("柜格更新失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除柜格 - 管理员功能
     */
    // @ApiOperation("删除柜格")
    @RequireRole(UserRole.ADMIN)
    @DeleteMapping("/{id}")
    public Result<String> deleteCompartment(@PathVariable Long id) {
        // 检查柜格是否存在
        LockerCompartment existing = lockerCompartmentService.getById(id);
        if (existing == null) {
            return Result.error("柜格不存在");
        }

        // 检查柜格是否被占用
        if ("OCCUPIED".equals(existing.getCompartmentStatus())) {
            return Result.error("柜格被占用，无法删除");
        }

        boolean success = lockerCompartmentService.removeById(id);
        if (success) {
            return Result.success("柜格删除成功");
        } else {
            return Result.error("柜格删除失败");
        }
    }

    /**
     * 批量更新柜格状态 - 管理员功能
     */
    // @ApiOperation("批量更新柜格状态")
    @RequireRole(UserRole.ADMIN)
    @PutMapping("/batch-status")
    public Result<String> batchUpdateStatus(@RequestBody Map<String, Object> requestBody) {
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) requestBody.get("ids");
        String status = (String) requestBody.get("status");

        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要更新的柜格");
        }

        if (status == null || status.trim().isEmpty()) {
            return Result.error("请选择目标状态");
        }

        // 验证状态值
        if (!"AVAILABLE".equals(status) && !"MAINTENANCE".equals(status) && !"OCCUPIED".equals(status)) {
            return Result.error("无效的状态值");
        }

        // 如果设置为占用状态，需要额外检查
        if ("OCCUPIED".equals(status)) {
            return Result.error("不能手动设置柜格为占用状态");
        }

        // 批量更新
        boolean success = lockerCompartmentService.lambdaUpdate()
                .in(LockerCompartment::getId, ids)
                .set(LockerCompartment::getCompartmentStatus, status)
                .update();

        if (success) {
            return Result.success("批量更新成功");
        } else {
            return Result.error("批量更新失败");
        }
    }

    /**
     * 获取可用柜格列表（按尺寸筛选） - 管理员功能
     */
    // @ApiOperation("获取可用柜格列表")
    @RequireRole(UserRole.ADMIN)
    @GetMapping("/available")
    public Result<List<LockerCompartment>> getAvailableCompartments(@RequestParam(required = false) String size) {
        List<LockerCompartment> compartments;
        
        if (size != null && !size.trim().isEmpty()) {
            compartments = lockerCompartmentService.lambdaQuery()
                    .eq(LockerCompartment::getCompartmentStatus, "AVAILABLE")
                    .eq(LockerCompartment::getCompartmentSize, size)
                    .list();
        } else {
            compartments = lockerCompartmentService.lambdaQuery()
                    .eq(LockerCompartment::getCompartmentStatus, "AVAILABLE")
                    .list();
        }
        
        return Result.success(compartments);
    }
}